function login(mpid) {
    console.log(mpid, '=========');
    wx.getSetting({
        success: (res) => {
            if (res.authSetting['scope.userInfo'] && getApp().mox.session.user.nickName) {
                onTesting(mpid);
            } else if (res.authSetting['scope.userInfo']) {
                getUserInfo(true, mpid);
            } else {
                wx.showModal({
                    title: '',
                    content: '请授权登录',
                    confirmText: '知道了',
                    showCancel: false
                });
            }
        }
    });
}

function getUserInfo(show_loading, mpid) {
    show_loading && wx.showLoading({ title: '登录中...',mask: true });
    if (wx.canIUse('getUserProfile')) {
        wx.getUserProfile({
            desc: '用于展示信息',
            success: (res) => {
                console.log(res);
                wx.hideLoading();
                let userInfo = res.userInfo;
                userInfo.nickName = userInfo.nickName;
                delete userInfo.nickName;
                userInfo.avatar = userInfo.avatarUrl;
                delete userInfo.avatarUrl;
                getApp().mox.session._setSessionCache(userInfo);
                onTesting(mpid);
            },
            fail: (err) => {
                loginFail(err);
                getApp().mox.stat('login_fail-' + err.errMsg);
            }
        });
    } else {
        wx.getUserInfo({
            success: (res) => {
                wx.hideLoading();
                let userInfo = res.userInfo;
                userInfo.nickname = userInfo.nickName;
                delete userInfo.nickName;
                userInfo.avatar = userInfo.avatarUrl;
                delete userInfo.avatarUrl;
                getApp().mox.session._setSessionCache(userInfo);
                onTesting(mpid);
            },
            fail: (err) => {
                loginFail(err);
                getApp().mox.stat('login_fail-' + err.errMsg);
            }
        });
    }
}

function loginFail(err) {
    const errMsg = 'getUserProfile:fail auth deny';
    const content =
        err.errMsg === errMsg
            ? '小程序需要您登录后才能继续使用哦...'
            : '登录出错，请检查网络稍候重试...';
    wx.hideLoading();
    wx.showModal({
        title: '',
        content: content,
        confirmText: '知道了',
        showCancel: false
    });
}

function onTesting(mpid) {
    wx.navigateTo({ url: `/pages/testing/testing?mpid=${mpid}` });
    getApp().mox.stat('begin_test');
    getApp().mox.stat('login_success');
}

export { login };
